#pragma once
#include <iostream>
#include <string>
#include <functional>
#include <unordered_map>
#include "TcpServer.hpp"
#include "HttpProtocol.hpp"



using http_handler_t = std::function<void(HttpRequest &, HttpResponse &)>;

class HttpServer
{
public:
    HttpServer(uint16_t port)
        : _tsvr(std::make_unique<TcpServer>(port))
    {
    }

    // HttpServer hs(8989,[&req,&res](std::string& s)
    // {

        
    //     req.Deserialization(s);
    //     res.Build(req);
    //     std::string ret;
    //     res.Serialize(&ret);
    //     return ret;
    // });
    std::string Handler(std::string &in)
    {
        HttpRequest req;
        HttpResponse res;
        req.Deserialization(in);

        //有参数
        if(req.Isexec())
        {
            std::string path = req.GetPath();
            std::cout<<"path:"<<path<<std::endl;

            if(mp.find(path) != mp.end())
            {
                mp[path](req,res);
            }
            else
            {
                std::cout<<"404了"<<std::endl;
                res.Build(req);
            }
        }
        else
        {
            res.Build(req);
        }

        std::string out;
        res.Serialize(&out);

        return out;
    }

    void Start()
    {
        _tsvr->Sethandler([this](std::string & in){return this->Handler(in);});
        _tsvr->InitServer();
        _tsvr->Start();
    }

    void SetMp(const std::string& k,const http_handler_t& v)
    {
        mp[k] = v;
    }

    ~HttpServer() = default;

private:
    std::shared_ptr<TcpServer> _tsvr;
    std::unordered_map<std::string,http_handler_t> mp;
};